//
//  CRPlayerManager.m
//  CRChatRoom
//
//  Created by CuiFengshuai on 15/11/29.
//  Copyright © 2015年 SecondGroup. All rights reserved.
//

#import "CRPlayerManager.h"

@interface CRPlayerManager ()
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@end

@implementation CRPlayerManager

static CRPlayerManager *s_defaultManager = nil;

+ (CRPlayerManager *) defaultManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_defaultManager = [[self alloc] init];
    });
    return s_defaultManager;
}

- (void)playWithUrlStr:(NSString *)urlStr view:(UIView *)view {
    // 创建item对象
    NSURL *url = [NSURL URLWithString:urlStr];
    AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:url];
    
    // 创建player对象
    AVPlayer *player = [AVPlayer playerWithPlayerItem:item];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    playerLayer.frame = view.bounds;
    playerLayer.backgroundColor = [[UIColor blackColor]CGColor];
    [view.layer addSublayer:playerLayer];
    
    // 监听播放完成的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndPlay) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    self.player = player;
    self.playerLayer = playerLayer;
}

- (void)didToPlay {
    [self.player play];
    self.isPlaying = YES;
}

- (void)didToStop {
    // 从父视图移除
    [self.playerLayer removeFromSuperlayer];
    [self.player pause];
    self.isPlaying = NO;
}
#pragma mark >>>> 事件监听方法
- (void)didEndPlay {
    
    [self didToStop];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:AVPlayerItemDidPlayToEndTimeNotification];
}
@end
